#!/usr/bin/env python3
import os
import re
import subprocess
import shlex


def get_duration(file):
    file = shlex.quote(file)
    cmd = 'ffmpeg -i ' + file + ' 2>&1 | grep Duration | awk \'{print $2}\''
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, shell=True)
    output, error = p.communicate()
    dur = output.decode()
    if '.' in dur:
        dur = dur[:dur.find('.')]
    return dur


def get_video_bitrate(file):
    file = shlex.quote(file)
    cmd = 'ffmpeg -i ' + file + ' 2>&1 | grep Stream | grep Video'
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, shell=True)
    output, error = p.communicate()
    return re.search(r'(\d+) kb/s,', output.decode()).groups()[0]


if __name__ == '__main__':
    buf = '[spoiler="Список выпусков"]\n'

    files = os.listdir(os.path.realpath('.'))
    files.sort()
    for file in files:
        if not file.endswith('.mp4'):
            continue

        title = re.sub(r'\.mp4$', '', file)
        title = title.replace('"', '')

        duration = get_duration(file)
        bitrate = get_video_bitrate(file)

        buf += f'[spoiler="{title}"]\n'
        buf += '>>>ОПИСАНИЕ<<<\n\n'

        buf += f'[b]Продолжительность:[/b] {duration}\n'
        buf += f'[b]Видео[/b]: H.265, 1280x720 (16:9), {bitrate} kbps, 25 fps\n'
        buf += '[b]Аудио[/b]: AAC, 128 kbps, 44.1 kHz, Stereo\n\n'

        buf += '[spoiler="Скриншоты"]\n>>>СКРИНШОТЫ<<<\n[/spoiler]\n\n'

        buf += '[/spoiler]\n\n'

    buf += '[/spoiler]'

    print(buf)
